

import LocalMap from "../../cfw/local/LocalMap";
/**
 * 一张表对应一个本地存储，以免读取次数太多
 * 造成性能浪费
 */
export default class LocalManager {
    private static ins: LocalManager;
    static instance(): LocalManager {
        if (!this.ins) {
            this.ins = new LocalManager()
        }
        return this.ins;
    }
    protected storage: { [k: string]: LocalMap } = {}

    remove(name: string) {
        let data: LocalMap = this.storage[name]
        if (data) {
            this.storage[name] = null;
        }
    }

    getData(name: string): LocalMap {
        let data: LocalMap = this.storage[name]
        if (!data) {
            data = new LocalMap(name, null)
            this.storage[name] = data;
        }
        return data;
    }

    getRowData(name: string, key: any) {
        let data: LocalMap = this.storage[name]
        if (!data) {
            return null;
        }
        let obj = data.get(key)
        if (obj) {
            return obj[key]
        }
        return null;
    }


    saveData(name: string) {
        let data: LocalMap = this.getData(name)
        data.save()
    }

    getValue(name: string, ID: string, key: number | string, initValue: any = 0) {
        let data: LocalMap = this.getData(name)
        // console.log('getValue getValue name ',name,ID,key,initValue,data)
        let obj = data.get(ID)

        if (obj == null) {
            obj = {}

        }
        if (obj[key] == undefined || obj[key] == null) {
            obj[key] = initValue;
        }
        return obj[key]
    }

    setValue(name: string, ID: string, key: number | string, value: any, isSave: boolean) {
        let data: LocalMap = this.getData(name)
        if (data) {
            let obj = data.get(ID)
            if (obj == null) {
                obj = {}
            }
            obj[key] = value;
            data.set(ID, obj, isSave)
        }
    }
}

